import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

// 导出数据转化为excel文件
// e: 接口给的二进制流文件 || 下载链接
// k: 导出文件的名称
// l: 导出的方式，1二进制流文件、2下载链接
export async function exportData(e,k,l){

	if(l == 1){
		let name = (k || new Date().getTime()) + '.xlsx';
		let ws = XLSX.utils.json_to_sheet(e);
		let wb = XLSX.utils.book_new();
		XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
		let xlsxData = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
		let blob = new Blob([xlsxData], {type: 'application/octet-stream'});
		saveAs(blob, name);
	}
	if(l == 2){
		let name = k || (new Date().getTime() + '.xlsx')
		// 根据配置文件url去下载excel
		let url = decodeURIComponent(e);
		if(!e.includes('http')){
			url = window.PLATFROM_CONFIG.baseUrl+decodeURIComponent(e);
		}
		if(window.location.hostname == 'localhost'){
			// 开发环境，打开新窗口下载
			window.open(url, '_blank')
			return
		}
		// 生产环境直接下载
		let a_link = document.createElement('a')
		fetch(url).then((res) => res.blob()).then((blob)=>{
			a_link.href = URL.createObjectURL(blob)
			a_link.download = name//下载的文件的名字
			document.body.appendChild(a_link)
			a_link.click()
		})
	}
}
